package com.lxk.config;

import com.lxk.Filter.TraceMdcFilter;
import com.lxk.dao.BlogDbDao;
import com.lxk.dao.CommentDao;
import com.lxk.interceptor.LoginInterceptor;
import com.lxk.interceptor.RecentBlogInterceptor;
import com.lxk.interceptor.ViewCountInterceptor;
import com.lxk.service.component.RedisClient;
import com.lxk.service.impl.UserServiceImpl;
import org.springframework.beans.BeansException;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * Created by Lxk on 2020/6/14.
 */
@Configuration
public class WebConfig implements WebMvcConfigurer, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Resource
    private RedisClient redisClient;

    @Resource
    private UserServiceImpl userService;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor(redisClient,userService))
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin")
                .excludePathPatterns("/admin/login");
        registry.addInterceptor(new RecentBlogInterceptor(applicationContext.getBean(BlogDbDao.class), applicationContext.getBean(CommentDao.class)))
                .addPathPatterns("/**");
        registry.addInterceptor(new ViewCountInterceptor(applicationContext.getBean(BlogDbDao.class)))
                .addPathPatterns("/blog/detail");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new TraceMdcFilter());
        registration.addUrlPatterns("/*");
        registration.setName("logMdcFilter");
        registration.setOrder(1);
        return registration;
    }

}
